package com.atnjupt.web;
/**
 * @author Wizarder
 * @create 2021-06-04 12:32
 */

import com.atnjupt.bean.User;
import com.atnjupt.service.impl.UserServiceImpl;
import com.atnjupt.utils.WebUtils;
import com.google.gson.Gson;
import org.apache.commons.beanutils.BeanUtils;

import javax.jws.soap.SOAPBinding;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * 代码优化二：
 * 利用反射动态获取表单隐藏value值，实现相应的功能
 */
public class UserServlet1 extends BaseServlet{
    private UserServiceImpl usi = new UserServiceImpl();

    protected void ajaxExistUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获取用户参数
        String username = request.getParameter("username");
        //2调用userService里的existUsername
        boolean existUsername = usi.existUsername(username);
        //3封装到map里
        Map<String,Object> map = new HashMap<>();
        map.put("existUsername",existUsername);
        Gson gson = new Gson();
        String json = gson.toJson(map);
        response.getWriter().write(json);

    }
    /**
     * 用户登陆功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //验证请求参数
        User loginUser = usi.login(new User(1, username, password, null));
        if(loginUser == null){
            //1失败跳转当前页面
            //用户或者密码错误，信息回显示客户端
            request.setAttribute("msg","用户或者密码错误");
            //保存客户端输入的内容
            request.setAttribute("username",username);
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);
        }else{
            //把用户名显示在登陆信息上
            request.getSession().setAttribute("user",loginUser);
            //2成功跳转登陆成功页面
            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request,response);
        }
    }
    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、消除session中的登陆信息（或者销毁session）
        request.getSession().invalidate();
        //2、请求重定向到首页或者注册页面，这里选择定向到首页
        response.sendRedirect(request.getContextPath() + "/");
//        System.out.println(request.getContextPath()+"/"); request.getContextPath()==>/book所以最好加个/
    }

    /**
     * 用户注册功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取session域中的图片验证码
        String imgCode = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //取消session域中保存的验证码信息
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //1获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

//        User user = new User();
//
//        user = WebUtils.copyToBean(request.getParameterMap(), user);

        //验证验证码-这里验证码写死==abcd
        if(imgCode != null && imgCode.equalsIgnoreCase(code)){
            //验证码正确
            //验证用户名是否存在
            boolean isExist = usi.existUsername(username);
//            System.out.println(isExist);
            if(isExist){
                //用户名已存在信息传回客户端
                request.setAttribute("msg","用户名已存在");
                request.setAttribute("password",password);
                request.setAttribute("email",email);
//                System.out.println("用户名存在");
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }else{
                //保存到数据库中，用户注册成功
                usi.registUser(new User(1,username,password,email));
                //跳转注册成功页面
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request,response);
            }

        }else{
            //验证码不同停留此界面
            //验证码输入错误信息回传客户端
            request.setAttribute("msg","验证码输入有误！");
            //保存用户输入的信息
            request.setAttribute("username",username);
            request.setAttribute("password",password);
            request.setAttribute("email",email);
//            System.out.println("验证码[" + code +"]不正确");
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }
    }


}
